import {
  getRegisterCode,
  goRegister,
  toLogin,
  reqUserInfo,
  reqLogout
} from '@/api/user'

const state = {
  code: '',
  token: localStorage.getItem('TOKEN'),
  userInfo: {}
}
const mutations = {
  SET_CODE (state, payload) {
    state.code = payload
  },
  SET_USER_TOKEN (state, payload) {
    state.token = payload
  },
  SET_USER_INFO (state, payload) {
    state.userInfo = payload
  },
  CLEAR(state){
    state.token = ''
    state.userInfo = {}
    localStorage.removeItem('TOKEN')
  }
}
const actions = {
  // 获取验证码
  async getCode ({ commit }, phone) {
    const res = await getRegisterCode(phone)
    if (res.code === 200) {
      commit('SET_CODE', res.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },
  // 注册
  async userRegister ({ commit }, data) {
    const res = await goRegister(data)
    if (res.code === 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },
  // 登录
  async userLogin ({ commit }, data) {
    const res =await toLogin(data)
    if (res.code === 200) {
      commit('SET_USER_TOKEN', res.data.token)
      localStorage.setItem('TOKEN', res.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },
  // 获取用户信息
  async getUserInfo ({commit}) {
    const res = await reqUserInfo()
    // console.log('res:', res)
    if (res.code === 200) {
      commit('SET_USER_INFO', res.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
  },
  // 退出登录
  async userLogout ({ commit }) {
    const res = await reqLogout()
    if (res.code === 200) {
      commit('CLEAR')
      return 'ok'
    }else{
      return Promise.reject(new Error('fail'))
    }
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
